class Solution
{
public:
    int findCircleNum(vector<vector<int>> &isConnected)
    {
        int n = isConnected.size();
        vector<int> unionFind(n);
        iota(unionFind.begin(), unionFind.end(), 0);
        std::function<int(int)> find = [&](int x)
        {
            if (unionFind[x] == x)
            {
                return x;
            }
            unionFind[x] = find(unionFind[x]);
            return unionFind[x];
        };
        auto join = [&](int x, int y)
        {
            unionFind[find(x)] = find(y);
        };
        int provinceCount = n;
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (isConnected[i][j] == 1)
                {
                    if (find(i) != find(j))
                    {
                        join(i, j);
                        --provinceCount;
                    }
                }
            }
        }
        return provinceCount;
    }
};